<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="logo">
        <el-icon size="24"><Medal /></el-icon>
        运动会管理系统
      </div>
      <div class="flex-grow"></div>
      <div class="user-info">
        <el-dropdown trigger="click">
          <div class="user-avatar">
            <el-avatar :size="40" :src="avatarUrl" icon="UserFilled"></el-avatar>
            <span class="username">{{ currentUser?.realName || '管理员' }}</span>
            <el-icon><ArrowDown /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleLogout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>

    <!-- 左侧导航栏 -->
    <nav class="sidebar">
      <div class="menu-item" :class="{ active: $route.path === '/admin' }" @click="navigateTo('/admin')">
        <el-icon><Monitor /></el-icon>
        <span>系统管理</span>
      </div>
      <div class="menu-item" :class="{ active: $route.path === '/admin/files' }" @click="navigateTo('/admin/files')">
        <el-icon><Folder /></el-icon>
        <span>文件管理</span>
      </div>
      <div class="menu-item active">
        <el-icon><Document /></el-icon>
        <span>证书管理</span>
      </div>
    </nav>

    <!-- 主要内容 -->
    <main class="content">
      <!-- 页面标题和操作按钮 -->
      <div class="page-header">
        <div class="page-title">
          <h1>证书管理</h1>
          <p class="page-desc">管理证书模板和记录，支持证书生成、预览和批量操作</p>
        </div>
        <div class="header-actions">
          <el-button type="success" @click="handleExportCertificates" :loading="exportLoading">
            <el-icon><Download /></el-icon> 导出证书列表
          </el-button>
          <el-button type="primary" @click="showGenerateDialog = true">
            <el-icon><Plus /></el-icon> 生成证书
          </el-button>
        </div>
      </div>

      <!-- 证书统计卡片 -->
      <el-row :gutter="20" class="statistics-row">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-item">
              <div class="stat-icon primary">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ certificateStats.totalCertificates }}</div>
                <div class="stat-label">证书总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-item">
              <div class="stat-icon success">
                <el-icon><Select /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ certificateStats.activeCertificates }}</div>
                <div class="stat-label">有效证书</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-item">
              <div class="stat-icon warning">
                <el-icon><Medal /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ certificateStats.awardCertificates }}</div>
                <div class="stat-label">获奖证书</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-item">
              <div class="stat-icon danger">
                <el-icon><CloseBold /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ certificateStats.revokedCertificates }}</div>
                <div class="stat-label">已撤销证书</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-tabs v-model="activeTab" type="border-card">
        <!-- 证书记录标签页 -->
        <el-tab-pane label="证书记录" name="records">
          <!-- 搜索和筛选区域 -->
          <div class="search-container">
            <el-form :model="searchForm" inline>
              <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :md="6">
                  <el-form-item label="证书编号">
                    <el-input
                      v-model="searchForm.certificateNo"
                      placeholder="请输入证书编号"
                      clearable
                      :prefix-icon="Document"
                      @keyup.enter="handleSearch">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                  <el-form-item label="证书类型">
                    <el-select
                      v-model="searchForm.certificateType"
                      placeholder="请选择证书类型"
                      clearable
                      style="width: 100%">
                      <el-option label="参赛证书" value="participation">
                        <el-tag type="primary" size="small">参赛证书</el-tag>
                      </el-option>
                      <el-option label="获奖证书" value="award">
                        <el-tag type="success" size="small">获奖证书</el-tag>
                      </el-option>
                      <el-option label="志愿者证书" value="volunteer">
                        <el-tag type="warning" size="small">志愿者证书</el-tag>
                      </el-option>
                      <el-option label="裁判证书" value="referee">
                        <el-tag type="info" size="small">裁判证书</el-tag>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                  <el-form-item label="获得者">
                    <el-input
                      v-model="searchForm.recipientName"
                      placeholder="请输入获得者姓名"
                      clearable
                      :prefix-icon="UserFilled"
                      @keyup.enter="handleSearch">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                  <el-form-item label="项目">
                    <el-input
                      v-model="searchForm.projectName"
                      placeholder="请输入项目名称"
                      clearable
                      :prefix-icon="List"
                      @keyup.enter="handleSearch">
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="12" :md="6">
                  <el-form-item>
                    <el-button type="primary" @click="handleSearch" :loading="loading">
                      <el-icon><Search /></el-icon> 搜索
                    </el-button>
                    <el-button @click="handleReset">
                      <el-icon><Refresh /></el-icon> 重置
                    </el-button>
                    <el-button type="info" @click="toggleAdvancedSearch">
                      <el-icon><Operation /></el-icon> {{ showAdvancedSearch ? '收起' : '高级' }}
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 高级搜索区域 -->
              <el-collapse-transition>
                <div v-show="showAdvancedSearch" class="advanced-search">
                  <el-divider content-position="left">高级搜索</el-divider>
                  <el-row :gutter="20">
                    <el-col :xs="24" :sm="12" :md="6">
                      <el-form-item label="奖项等级">
                        <el-select
                          v-model="searchForm.awardLevel"
                          placeholder="请选择奖项等级"
                          clearable
                          style="width: 100%">
                          <el-option label="金牌" value="金牌" />
                          <el-option label="银牌" value="银牌" />
                          <el-option label="铜牌" value="铜牌" />
                          <el-option label="参与奖" value="参与奖" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="6">
                      <el-form-item label="颁发时间">
                        <el-date-picker
                          v-model="searchForm.dateRange"
                          type="daterange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          style="width: 100%"
                          format="YYYY-MM-DD"
                          value-format="YYYY-MM-DD">
                        </el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="6">
                      <el-form-item label="证书状态">
                        <el-select
                          v-model="searchForm.status"
                          placeholder="请选择证书状态"
                          clearable
                          style="width: 100%">
                          <el-option label="正常" value="normal">
                            <el-tag type="success" size="small">正常</el-tag>
                          </el-option>
                          <el-option label="已撤销" value="revoked">
                            <el-tag type="danger" size="small">已撤销</el-tag>
                          </el-option>
                          <el-option label="已重发" value="reissued">
                            <el-tag type="warning" size="small">已重发</el-tag>
                          </el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </div>
              </el-collapse-transition>
            </el-form>
          </div>
          <!-- 证书数据表格 -->
          <el-card class="table-card" shadow="hover">
            <!-- 工具栏 -->
            <div class="table-toolbar">
              <div class="table-info">
                <span class="table-title">证书记录</span>
                <el-tag type="info" size="small">共 {{ pagination.total }} 条记录</el-tag>
              </div>
              <div class="table-actions">
                <el-button-group>
                  <el-button
                    :size="tableSize"
                    @click="tableSize = 'large'"
                    :class="{ 'is-active': tableSize === 'large' }">
                    大
                  </el-button>
                  <el-button
                    :size="tableSize"
                    @click="tableSize = 'default'"
                    :class="{ 'is-active': tableSize === 'default' }">
                    中
                  </el-button>
                  <el-button
                    :size="tableSize"
                    @click="tableSize = 'small'"
                    :class="{ 'is-active': tableSize === 'small' }">
                    小
                  </el-button>
                </el-button-group>
                <el-button
                  :icon="RefreshRight"
                  @click="fetchRecordList"
                  :loading="loading"
                  circle>
                </el-button>
              </div>
            </div>

            <!-- 表格主体 -->
            <el-table
              :data="recordList"
              v-loading="loading"
              :height="tableHeight"
              stripe
              border
              :size="tableSize"
              @selection-change="handleSelectionChange"
              style="width: 100%">
              <el-table-column type="selection" width="55" align="center" fixed="left"></el-table-column>
              <el-table-column prop="certificateNo" label="证书编号" width="180" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <el-link type="primary" @click="handleViewCertificateDetail(scope.row)">
                    {{ scope.row.certificateNo }}
                  </el-link>
                </template>
              </el-table-column>
              <el-table-column prop="certificateType" label="类型" width="120" align="center">
                <template #default="scope">
                  <el-tag :type="getCertificateTypeTag(scope.row.certificateType)" size="small">
                    {{ getCertificateTypeText(scope.row.certificateType) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="recipientName" label="获得者" width="120" align="center">
                <template #default="scope">
                  <el-avatar :size="24" icon="UserFilled"></el-avatar>
                  <span style="margin-left: 8px">{{ scope.row.recipientName }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="recipientDepartment" label="部门/班级" width="150" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="projectName" label="项目" width="150" align="center" show-overflow-tooltip></el-table-column>
              <el-table-column prop="awardLevel" label="奖项等级" width="100" align="center">
                <template #default="scope">
                  <el-tag v-if="scope.row.awardLevel" :type="getAwardLevelTag(scope.row.awardLevel)" size="small">
                    {{ scope.row.awardLevel }}
                  </el-tag>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="issueDate" label="颁发时间" width="160" align="center">
                <template #default="scope">
                  {{ formatDateTime(scope.row.issueDate) }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100" align="center">
                <template #default="scope">
                  <el-tag :type="getStatusTag(scope.row.status)" size="small">
                    {{ getStatusText(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="320" align="center" fixed="right">
                <template #default="scope">
                  <el-button-group>
                    <el-tooltip content="查看详情" placement="top">
                      <el-button
                        type="primary"
                        :icon="View"
                        size="small"
                        @click="handleViewCertificateDetail(scope.row)">
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="预览" placement="top">
                      <el-button
                        type="success"
                        :icon="ZoomIn"
                        size="small"
                        @click="handlePreviewCertificate(scope.row)">
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="下载" placement="top">
                      <el-button
                        type="primary"
                        :icon="Download"
                        size="small"
                        @click="handleDownload(scope.row)">
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="验证" placement="top">
                      <el-button
                        type="info"
                        :icon="Check"
                        size="small"
                        @click="handleValidate(scope.row)">
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="重新生成" placement="top" v-if="scope.row.status === 'normal'">
                      <el-button
                        type="warning"
                        :icon="RefreshRight"
                        size="small"
                        @click="handleRegenerate(scope.row)">
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="撤销" placement="top" v-if="scope.row.status === 'normal'">
                      <el-button
                        type="danger"
                        :icon="CloseBold"
                        size="small"
                        @click="handleRevoke(scope.row)">
                      </el-button>
                    </el-tooltip>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>

            <!-- 分页控制 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background>
              </el-pagination>
            </div>

            <!-- 批量操作栏 -->
            <div class="batch-operations" v-if="selectedCertificates.length > 0">
              <div class="batch-info">
                <el-icon><Select /></el-icon>
                <span>已选择 {{ selectedCertificates.length }} 项</span>
              </div>
              <div class="batch-actions">
                <el-button-group>
                  <el-button type="primary" @click="handleBatchDownload" :loading="batchLoading">
                    <el-icon><Download /></el-icon> 批量下载
                  </el-button>
                  <el-button type="success" @click="handleBatchValidate" :loading="batchLoading">
                    <el-icon><Check /></el-icon> 批量验证
                  </el-button>
                  <el-button type="warning" @click="handleBatchRegenerate" :loading="batchLoading">
                    <el-icon><RefreshRight /></el-icon> 批量重新生成
                  </el-button>
                  <el-button type="danger" @click="handleBatchRevoke" :loading="batchLoading">
                    <el-icon><CloseBold /></el-icon> 批量撤销
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 证书模板标签页 -->
        <el-tab-pane label="证书模板" name="templates">
          <!-- 模板操作栏 -->
          <div class="template-header">
            <div class="template-actions">
              <el-button type="primary" @click="showTemplateDialog = true">
                <el-icon><Plus /></el-icon> 新建模板
              </el-button>
              <el-button type="success" @click="handleImportTemplate">
                <el-icon><Upload /></el-icon> 导入模板
              </el-button>
            </div>
            <div class="template-filter">
              <el-select
                v-model="templateFilter"
                placeholder="筛选模板类型"
                clearable
                @change="filterTemplates"
                style="width: 200px">
                <el-option label="全部" value="" />
                <el-option label="参赛证书" value="participation" />
                <el-option label="获奖证书" value="award" />
                <el-option label="志愿者证书" value="volunteer" />
                <el-option label="裁判证书" value="referee" />
              </el-select>
            </div>
          </div>

          <!-- 模板网格布局 -->
          <el-row :gutter="20" class="template-grid">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="template in filteredTemplateList" :key="template.id">
              <el-card class="template-card" shadow="hover" :body-style="{ padding: '0px' }">
                <div class="template-preview">
                  <div class="template-thumbnail">
                    <el-image
                      :src="template.thumbnailUrl || '/img/certificate-template-placeholder.png'"
                      fit="cover"
                      style="width: 100%; height: 200px;">
                      <template #error>
                        <div class="image-error">
                          <el-icon size="48"><Picture /></el-icon>
                          <p>暂无预览</p>
                        </div>
                      </template>
                    </el-image>
                  </div>
                  <div class="template-info">
                    <div class="template-name">{{ template.templateName }}</div>
                    <div class="template-meta">
                      <el-tag :type="getCertificateTypeTag(template.templateType)" size="small">
                        {{ getCertificateTypeText(template.templateType) }}
                      </el-tag>
                      <el-tag v-if="template.isDefault" type="success" size="small">默认</el-tag>
                      <el-tag :type="template.status === 'active' ? 'success' : 'danger'" size="small">
                        {{ template.status === 'active' ? '启用' : '禁用' }}
                      </el-tag>
                    </div>
                    <div class="template-description">{{ template.description || '暂无描述' }}</div>
                    <div class="template-footer">
                      <span class="template-creator">创建人: {{ template.createUserName }}</span>
                      <span class="template-date">{{ formatDateTime(template.createdAt) }}</span>
                    </div>
                  </div>
                </div>
                <div class="template-actions-overlay">
                  <el-button-group>
                    <el-tooltip content="预览" placement="top">
                      <el-button
                        type="success"
                        :icon="ZoomIn"
                        size="small"
                        @click="handlePreviewTemplate(template)">
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="编辑" placement="top">
                      <el-button
                        type="primary"
                        :icon="Edit"
                        size="small"
                        @click="handleEditTemplate(template)">
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="设为默认" placement="top" v-if="!template.isDefault">
                      <el-button
                        type="warning"
                        :icon="Star"
                        size="small"
                        @click="handleSetDefault(template)">
                      </el-button>
                    </el-tooltip>
                    <el-tooltip :content="template.status === 'active' ? '禁用' : '启用'" placement="top">
                      <el-button
                        :type="template.status === 'active' ? 'warning' : 'success'"
                        :icon="template.status === 'active' ? 'CloseBold' : 'Check'"
                        size="small"
                        @click="handleToggleTemplateStatus(template)">
                      </el-button>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                      <el-button
                        type="danger"
                        :icon="Delete"
                        size="small"
                        @click="handleDeleteTemplate(template)">
                      </el-button>
                    </el-tooltip>
                  </el-button-group>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>

    <!-- 生成证书对话框 -->
    <el-dialog
      v-model="showGenerateDialog"
      title="生成证书"
      width="700px"
      :close-on-click-modal="false"
      destroy-on-close>
      <el-steps :active="generateStep" finish-status="success" align-center class="generate-steps">
        <el-step title="选择类型" />
        <el-step title="选择对象" />
        <el-step title="确认信息" />
      </el-steps>

      <div class="generate-content">
        <!-- 步骤1: 选择证书类型 -->
        <div v-if="generateStep === 0" class="step-content">
          <el-form :model="generateForm" :rules="generateFormRules" ref="generateFormRef" label-width="120px">
            <el-form-item label="证书类型" prop="certificateType">
              <el-radio-group v-model="generateForm.certificateType" @change="handleCertificateTypeChange">
                <el-radio label="participation" class="certificate-type-radio">
                  <div class="certificate-type-option">
                    <el-icon class="certificate-type-icon"><User /></el-icon>
                    <div class="certificate-type-text">
                      <div class="certificate-type-title">参赛证书</div>
                      <div class="certificate-type-desc">颁发给参与运动会的运动员</div>
                    </div>
                  </div>
                </el-radio>
                <el-radio label="award" class="certificate-type-radio">
                  <div class="certificate-type-option">
                    <el-icon class="certificate-type-icon"><Medal /></el-icon>
                    <div class="certificate-type-text">
                      <div class="certificate-type-title">获奖证书</div>
                      <div class="certificate-type-desc">颁发给获得奖项的运动员</div>
                    </div>
                  </div>
                </el-radio>
                <el-radio label="volunteer" class="certificate-type-radio">
                  <div class="certificate-type-option">
                    <el-icon class="certificate-type-icon"><UserFilled /></el-icon>
                    <div class="certificate-type-text">
                      <div class="certificate-type-title">志愿者证书</div>
                      <div class="certificate-type-desc">颁发给参与志愿服务的人员</div>
                    </div>
                  </div>
                </el-radio>
                <el-radio label="referee" class="certificate-type-radio">
                  <div class="certificate-type-option">
                    <el-icon class="certificate-type-icon"><Whistle /></el-icon>
                    <div class="certificate-type-text">
                      <div class="certificate-type-title">裁判证书</div>
                      <div class="certificate-type-desc">颁发给参与裁判工作的人员</div>
                    </div>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>

        <!-- 步骤2: 选择对象 -->
        <div v-if="generateStep === 1" class="step-content">
          <el-form :model="generateForm" label-width="120px">
            <el-form-item label="获得者" required>
              <el-select
                v-model="generateForm.userIds"
                multiple
                filterable
                placeholder="请选择获得者"
                style="width: 100%">
                <el-option
                  v-for="user in userOptions"
                  :key="user.value"
                  :label="user.label"
                  :value="user.value">
                  <div class="user-option">
                    <el-avatar :size="24" :src="user.avatar" icon="UserFilled"></el-avatar>
                    <span style="margin-left: 8px">{{ user.label }}</span>
                    <el-tag size="small" style="margin-left: 8px">{{ user.department }}</el-tag>
                  </div>
                </el-option>
              </el-select>
              <div class="form-tip">
                <el-icon><InfoFilled /></el-icon>
                <span>已选择 {{ generateForm.userIds.length }} 位获得者</span>
              </div>
            </el-form-item>

            <el-form-item label="关联项目" v-if="generateForm.certificateType === 'participation' || generateForm.certificateType === 'award'" required>
              <el-select
                v-model="generateForm.projectId"
                filterable
                placeholder="请选择项目"
                style="width: 100%">
                <el-option
                  v-for="project in projectOptions"
                  :key="project.value"
                  :label="project.label"
                  :value="project.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="奖项等级" v-if="generateForm.certificateType === 'award'" required>
              <el-select
                v-model="generateForm.awardLevel"
                placeholder="请选择奖项等级"
                style="width: 100%">
                <el-option label="金牌" value="金牌">
                  <el-tag type="warning" size="small">金牌</el-tag>
                </el-option>
                <el-option label="银牌" value="银牌">
                  <el-tag type="info" size="small">银牌</el-tag>
                </el-option>
                <el-option label="铜牌" value="铜牌">
                  <el-tag type="success" size="small">铜牌</el-tag>
                </el-option>
                <el-option label="参与奖" value="参与奖">
                  <el-tag type="primary" size="small">参与奖</el-tag>
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="奖项ID" v-if="generateForm.certificateType === 'award'" required>
              <el-input-number
                v-model="generateForm.awardId"
                :min="1"
                placeholder="请输入奖项ID"
                style="width: 100%" />
            </el-form-item>

            <el-form-item label="模板选择">
              <el-select
                v-model="generateForm.templateId"
                placeholder="请选择证书模板"
                style="width: 100%">
                <el-option
                  v-for="template in availableTemplates"
                  :key="template.id"
                  :label="template.templateName"
                  :value="template.id">
                  <div class="template-option">
                    <span>{{ template.templateName }}</span>
                    <el-tag v-if="template.isDefault" type="success" size="small" style="margin-left: 8px">默认</el-tag>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <!-- 步骤3: 确认信息 -->
        <div v-if="generateStep === 2" class="step-content">
          <el-descriptions title="证书生成预览" :column="2" border>
            <el-descriptions-item label="证书类型">
              <el-tag :type="getCertificateTypeTag(generateForm.certificateType)">
                {{ getCertificateTypeText(generateForm.certificateType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="获得者数量">
              {{ generateForm.userIds.length }} 人
            </el-descriptions-item>
            <el-descriptions-item label="项目" v-if="generateForm.projectId">
              {{ getProjectName(generateForm.projectId) }}
            </el-descriptions-item>
            <el-descriptions-item label="奖项等级" v-if="generateForm.awardLevel">
              <el-tag :type="getAwardLevelTag(generateForm.awardLevel)">
                {{ generateForm.awardLevel }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="使用模板" :span="2">
              {{ getTemplateName(generateForm.templateId) }}
            </el-descriptions-item>
            <el-descriptions-item label="获得者列表" :span="2">
              <el-tag
                v-for="userId in generateForm.userIds"
                :key="userId"
                style="margin-right: 8px; margin-bottom: 8px;"
                size="small">
                {{ getUserName(userId) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showGenerateDialog = false">取消</el-button>
          <el-button v-if="generateStep > 0" @click="generateStep--">上一步</el-button>
          <el-button
            v-if="generateStep < 2"
            type="primary"
            @click="nextGenerateStep"
            :disabled="!canProceedToNextStep">
            下一步
          </el-button>
          <el-button
            v-if="generateStep === 2"
            type="primary"
            @click="handleGenerate"
            :loading="generating">
            {{ generating ? '生成中...' : '确定生成' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 证书模板对话框 -->
    <el-dialog
      v-model="showTemplateDialog"
      :title="templateForm.id ? '编辑模板' : '新建模板'"
      width="800px"
      :close-on-click-modal="false"
      destroy-on-close>
      <el-form :model="templateForm" :rules="templateFormRules" ref="templateFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input v-model="templateForm.templateName" placeholder="请输入模板名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板类型" prop="templateType">
              <el-select v-model="templateForm.templateType" placeholder="请选择模板类型" style="width: 100%">
                <el-option label="参赛证书" value="participation" />
                <el-option label="获奖证书" value="award" />
                <el-option label="志愿者证书" value="volunteer" />
                <el-option label="裁判证书" value="referee" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模板描述">
          <el-input
            v-model="templateForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
            maxlength="200"
            show-word-limit />
        </el-form-item>
        <el-form-item label="模板内容" prop="templateContent">
          <el-input
            v-model="templateForm.templateContent"
            type="textarea"
            :rows="8"
            placeholder="请输入模板内容（支持变量：{name}, {project}, {award}, {date}, {school}等）"
            maxlength="1000"
            show-word-limit />
        </el-form-item>
        <el-form-item label="模板样式">
          <el-tabs v-model="templateStyleTab" type="border-card">
            <el-tab-pane label="基本设置" name="basic">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="页面方向">
                    <el-radio-group v-model="templateForm.orientation">
                      <el-radio label="portrait">纵向</el-radio>
                      <el-radio label="landscape">横向</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="页面大小">
                    <el-select v-model="templateForm.pageSize" style="width: 100%">
                      <el-option label="A4" value="A4" />
                      <el-option label="A3" value="A3" />
                      <el-option label="Letter" value="Letter" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="边距设置">
                <el-row :gutter="10">
                  <el-col :span="6">
                    <el-input-number v-model="templateForm.marginTop" placeholder="上" :min="0" style="width: 100%" />
                  </el-col>
                  <el-col :span="6">
                    <el-input-number v-model="templateForm.marginRight" placeholder="右" :min="0" style="width: 100%" />
                  </el-col>
                  <el-col :span="6">
                    <el-input-number v-model="templateForm.marginBottom" placeholder="下" :min="0" style="width: 100%" />
                  </el-col>
                  <el-col :span="6">
                    <el-input-number v-model="templateForm.marginLeft" placeholder="左" :min="0" style="width: 100%" />
                  </el-col>
                </el-row>
              </el-form-item>
            </el-tab-pane>
            <el-tab-pane label="字体设置" name="font">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="标题字体">
                    <el-select v-model="templateForm.titleFont" style="width: 100%">
                      <el-option label="宋体" value="SimSun" />
                      <el-option label="微软雅黑" value="Microsoft YaHei" />
                      <el-option label="黑体" value="SimHei" />
                      <el-option label="楷体" value="KaiTi" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="正文字体">
                    <el-select v-model="templateForm.contentFont" style="width: 100%">
                      <el-option label="宋体" value="SimSun" />
                      <el-option label="微软雅黑" value="Microsoft YaHei" />
                      <el-option label="黑体" value="SimHei" />
                      <el-option label="楷体" value="KaiTi" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="标题字号">
                    <el-input-number v-model="templateForm.titleSize" :min="12" :max="72" style="width: 100%" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="正文字号">
                    <el-input-number v-model="templateForm.contentSize" :min="8" :max="48" style="width: 100%" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="颜色设置" name="color">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="背景颜色">
                    <el-color-picker v-model="templateForm.backgroundColor" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="边框颜色">
                    <el-color-picker v-model="templateForm.borderColor" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="标题颜色">
                    <el-color-picker v-model="templateForm.titleColor" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="文字颜色">
                    <el-color-picker v-model="templateForm.textColor" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        <el-form-item label="设为默认">
          <el-switch v-model="templateForm.isDefault" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showTemplateDialog = false">取消</el-button>
          <el-button type="info" @click="handlePreviewTemplateForm">预览</el-button>
          <el-button type="primary" @click="handleSaveTemplate">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 证书详情对话框 -->
    <el-dialog
      title="证书详情"
      v-model="showCertificateDetailDialog"
      width="600px">
      <div v-if="currentCertificate" class="certificate-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="证书编号">{{ currentCertificate.certificateNo }}</el-descriptions-item>
          <el-descriptions-item label="证书类型">
            <el-tag :type="getCertificateTypeTag(currentCertificate.certificateType)">
              {{ getCertificateTypeText(currentCertificate.certificateType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="获得者">{{ currentCertificate.recipientName }}</el-descriptions-item>
          <el-descriptions-item label="部门/班级">{{ currentCertificate.recipientDepartment }}</el-descriptions-item>
          <el-descriptions-item label="项目">{{ currentCertificate.projectName }}</el-descriptions-item>
          <el-descriptions-item label="奖项等级">{{ currentCertificate.awardLevel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="颁发时间">{{ formatDateTime(currentCertificate.issueDate) }}</el-descriptions-item>
          <el-descriptions-item label="证书状态">
            <el-tag :type="getStatusTag(currentCertificate.status)">
              {{ getStatusText(currentCertificate.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 证书预览 -->
        <div class="certificate-preview" v-if="certificatePreviewUrl">
          <el-divider content-position="left">证书预览</el-divider>
          <el-image
            :src="certificatePreviewUrl"
            fit="contain"
            style="width: 100%; max-height: 400px;"
            :preview-src-list="[certificatePreviewUrl]"
            preview-teleported>
          </el-image>
        </div>
      </div>
    </el-dialog>

    <!-- 证书预览对话框 -->
    <el-dialog
      title="证书预览"
      v-model="showCertificatePreviewDialog"
      width="80%">
      <div class="certificate-preview-container">
        <el-image
          :src="certificatePreviewUrl"
          fit="contain"
          style="width: 100%; height: 600px;"
          :preview-src-list="[certificatePreviewUrl]"
          preview-teleported>
        </el-image>
      </div>
    </el-dialog>

    <!-- 证书验证对话框 -->
    <el-dialog
      title="证书验证"
      v-model="showValidateDialog"
      width="600px">
      <div v-if="validateResult">
        <el-alert
          :title="validateResult.valid ? '证书验证通过' : '证书验证失败'"
          :type="validateResult.valid ? 'success' : 'error'"
          :closable="false"
          show-icon
          style="margin-bottom: 20px">
        </el-alert>
        <el-descriptions v-if="validateResult.certificateInfo" :column="2" border>
          <el-descriptions-item label="证书编号">
            {{ validateResult.certificateInfo.certificateNo }}
          </el-descriptions-item>
          <el-descriptions-item label="证书类型">
            <el-tag :type="getCertificateTypeTag(validateResult.certificateInfo.certificateType)">
              {{ getCertificateTypeText(validateResult.certificateInfo.certificateType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="获得者">{{ validateResult.certificateInfo.recipientName }}</el-descriptions-item>
          <el-descriptions-item label="部门/班级">{{ validateResult.certificateInfo.recipientDepartment }}</el-descriptions-item>
          <el-descriptions-item label="项目">{{ validateResult.certificateInfo.projectName }}</el-descriptions-item>
          <el-descriptions-item label="奖项等级">{{ validateResult.certificateInfo.awardLevel || '-' }}</el-descriptions-item>
          <el-descriptions-item label="颁发时间">{{ formatDateTime(validateResult.certificateInfo.issueDate) }}</el-descriptions-item>
          <el-descriptions-item label="证书状态">
            <el-tag :type="getStatusTag(validateResult.certificateInfo.status)">
              {{ getStatusText(validateResult.certificateInfo.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="验证时间" :span="2">{{ formatDateTime(validateResult.validateTime) }}</el-descriptions-item>
          <el-descriptions-item label="验证码" :span="2">
            <el-tag type="info">{{ validateResult.verifyCode }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div v-else class="validate-form">
        <el-form :model="validateForm" label-width="100px">
          <el-form-item label="证书编号" required>
            <el-input v-model="validateForm.certificateNo" placeholder="请输入证书编号" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleValidateCertificate" :loading="validating">
              验证证书
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    </main>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  // 图标组件
  Medal, Document, Monitor, ArrowDown, SwitchButton, Download, Plus, Search,
  Refresh, Operation, UserFilled, View, Delete, Select, Check, RefreshRight,
  CloseBold, ZoomIn, Upload, Edit, Star, List, InfoFilled, User, Whistle,
  Picture, Folder
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

// 导入API接口
import {
  getRecordList, generateParticipationCertificate, generateAwardCertificate,
  generateVolunteerCertificate, generateRefereeCertificate, batchGenerateCertificates,
  regenerateCertificate, revokeCertificate, downloadCertificate, validateCertificate
} from '@/api/certificate'
import {
  getTemplateList, createTemplate, updateTemplate, setAsDefault, deleteTemplate
} from '@/api/certificate'

// 路由和状态管理
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const loading = ref(false)
const templateLoading = ref(false)
const generating = ref(false)
const validating = ref(false)
const exportLoading = ref(false)
const batchLoading = ref(false)
const recordList = ref([])
const templateList = ref([])
const filteredTemplateList = ref([])
const selectedCertificates = ref([])
const showGenerateDialog = ref(false)
const showTemplateDialog = ref(false)
const showValidateDialog = ref(false)
const showCertificateDetailDialog = ref(false)
const showCertificatePreviewDialog = ref(false)
const showAdvancedSearch = ref(false)
const tableSize = ref('default')
const activeTab = ref('records')
const generateStep = ref(0)
const templateStyleTab = ref('basic')
const templateFilter = ref('')
const validateResult = ref(null)
const certificatePreviewUrl = ref('')
const currentCertificate = ref(null)

// 表格高度
const tableHeight = ref(600)

// 生成表单引用
const generateFormRef = ref()
const templateFormRef = ref()

// 计算属性
const currentUser = computed(() => authStore.userInfo || JSON.parse(localStorage.getItem('user')))
const avatarUrl = computed(() => '/img/jstu1.webp')

// 搜索表单
const searchForm = reactive({
  certificateNo: '',
  certificateType: '',
  recipientName: '',
  projectName: '',
  awardLevel: '',
  status: '',
  dateRange: null
})

// 生成证书表单
const generateForm = reactive({
  certificateType: '',
  userIds: [],
  projectId: null,
  awardId: null,
  awardLevel: '',
  templateId: null
})

// 模板表单
const templateForm = reactive({
  id: null,
  templateName: '',
  templateType: '',
  description: '',
  templateContent: '',
  isDefault: false,
  orientation: 'portrait',
  pageSize: 'A4',
  marginTop: 20,
  marginRight: 20,
  marginBottom: 20,
  marginLeft: 20,
  titleFont: 'Microsoft YaHei',
  contentFont: 'SimSun',
  titleSize: 24,
  contentSize: 14,
  backgroundColor: '#FFFFFF',
  borderColor: '#000000',
  titleColor: '#000000',
  textColor: '#000000'
})

// 验证表单
const validateForm = reactive({
  certificateNo: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 证书统计
const certificateStats = reactive({
  totalCertificates: 0,
  activeCertificates: 0,
  awardCertificates: 0,
  revokedCertificates: 0
})

// 表单验证规则
const generateFormRules = reactive({
  certificateType: [
    { required: true, message: '请选择证书类型', trigger: 'change' }
  ]
})

const templateFormRules = reactive({
  templateName: [
    { required: true, message: '请输入模板名称', trigger: 'blur' },
    { min: 2, max: 50, message: '模板名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  templateType: [
    { required: true, message: '请选择模板类型', trigger: 'change' }
  ],
  templateContent: [
    { required: true, message: '请输入模板内容', trigger: 'blur' },
    { min: 10, max: 1000, message: '模板内容长度在 10 到 1000 个字符', trigger: 'blur' }
  ]
})

// 模拟数据 - 实际项目中应从API获取
const userOptions = ref([
  { value: 1, label: '张三', department: '计算机学院', avatar: '' },
  { value: 2, label: '李四', department: '物理学院', avatar: '' },
  { value: 3, label: '王五', department: '化学学院', avatar: '' },
  { value: 4, label: '赵六', department: '数学学院', avatar: '' }
])

const projectOptions = ref([
  { value: 1, label: '100米短跑' },
  { value: 2, label: '跳远' },
  { value: 3, label: '篮球' },
  { value: 4, label: '足球' },
  { value: 5, label: '乒乓球' }
])

// 计算可用模板
const availableTemplates = computed(() => {
  if (!generateForm.certificateType) return templateList.value
  return templateList.value.filter(template => template.templateType === generateForm.certificateType)
})

// 是否可以进入下一步
const canProceedToNextStep = computed(() => {
  if (generateStep.value === 0) {
    return generateForm.certificateType
  } else if (generateStep.value === 1) {
    return generateForm.userIds.length > 0 &&
           (generateForm.certificateType !== 'participation' && generateForm.certificateType !== 'award' || generateForm.projectId) &&
           (generateForm.certificateType !== 'award' || generateForm.awardLevel)
  }
  return true
})

  // 获取证书记录列表
const fetchRecordList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    const response = await getRecordList(pagination.currentPage, pagination.pageSize, params)
    if (response.code === 200) {
      recordList.value = response.data.records || []
      pagination.total = response.data.total || 0
    }
  } catch (error) {
    ElMessage.error('获取证书记录列表失败')
  } finally {
    loading.value = false
  }
}

// 获取模板列表
const fetchTemplateList = async () => {
  templateLoading.value = true
  try {
    const response = await getTemplateList(1, 1000, {}) // 获取所有模板
    if (response.code === 200) {
      templateList.value = response.data.records || []
      filteredTemplateList.value = templateList.value
    }
  } catch (error) {
    ElMessage.error('获取模板列表失败')
  } finally {
    templateLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchRecordList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    certificateNo: '',
    certificateType: '',
    recipientName: '',
    projectName: '',
    awardLevel: '',
    status: '',
    dateRange: null
  })
  pagination.currentPage = 1
  fetchRecordList()
}

// 分页改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchRecordList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchRecordList()
}

// 生成证书
const handleGenerate = async () => {
  if (!generateForm.certificateType || generateForm.userIds.length === 0) {
    ElMessage.warning('请填写完整的生成信息')
    return
  }

  generating.value = true
  try {
    const params = {
      userIds: generateForm.userIds,
      certificateType: generateForm.certificateType,
      projectId: generateForm.projectId,
      awardId: generateForm.awardId,
      awardLevel: generateForm.awardLevel
    }

    if (generateForm.userIds.length === 1) {
      // 单个生成
      const userId = generateForm.userIds[0]
      switch (generateForm.certificateType) {
        case 'participation':
          await generateParticipationCertificate(userId, generateForm.projectId)
          break
        case 'award':
          await generateAwardCertificate(userId, generateForm.projectId, generateForm.awardId, generateForm.awardLevel)
          break
        case 'volunteer':
          await generateVolunteerCertificate(userId)
          break
        case 'referee':
          await generateRefereeCertificate(userId)
          break
      }
    } else {
      // 批量生成
      await batchGenerateCertificates(params)
    }

    ElMessage.success('证书生成成功')
    showGenerateDialog.value = false
    // 重置表单
    Object.assign(generateForm, {
      certificateType: '',
      userIds: [],
      projectId: null,
      awardId: null,
      awardLevel: '',
      templateId: null
    })
    fetchRecordList()
  } catch (error) {
    ElMessage.error('证书生成失败')
  } finally {
    generating.value = false
  }
}

// 下载证书
const handleDownload = async (record) => {
  try {
    const response = await downloadCertificate(record.id)
    const blob = new Blob([response.data], { type: 'application/pdf' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `证书_${record.certificateNo}.pdf`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 验证证书
const handleValidate = async (record) => {
  try {
    const response = await validateCertificate(record.certificateNo)
    if (response.code === 200) {
      validateResult.value = response.data
      showValidateDialog.value = true
    }
  } catch (error) {
    ElMessage.error('验证失败')
  }
}

// 重新生成证书
const handleRegenerate = async (record) => {
  try {
    await ElMessageBox.confirm('确定要重新生成这个证书吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await regenerateCertificate(record.id)
    ElMessage.success('证书重新生成成功')
    fetchRecordList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重新生成失败')
    }
  }
}

// 撤销证书
const handleRevoke = async (record) => {
  try {
    await ElMessageBox.confirm('确定要撤销这个证书吗？撤销后无法恢复。', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await revokeCertificate(record.id)
    ElMessage.success('证书撤销成功')
    fetchRecordList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('撤销失败')
    }
  }
}

// 编辑模板
const handleEditTemplate = (template) => {
  Object.assign(templateForm, {
    id: template.id,
    templateName: template.templateName,
    templateType: template.templateType,
    description: template.description,
    templateContent: template.templateContent,
    isDefault: template.isDefault
  })
  showTemplateDialog.value = true
}

// 保存模板
const handleSaveTemplate = async () => {
  if (!templateForm.templateName || !templateForm.templateType) {
    ElMessage.warning('请填写完整的模板信息')
    return
  }

  try {
    if (templateForm.id) {
      // 更新模板
      await updateTemplate(templateForm)
      ElMessage.success('模板更新成功')
    } else {
      // 创建模板
      await createTemplate(templateForm)
      ElMessage.success('模板创建成功')
    }

    showTemplateDialog.value = false
    // 重置表单
    Object.assign(templateForm, {
      id: null,
      templateName: '',
      templateType: '',
      description: '',
      templateContent: '',
      isDefault: false
    })
    fetchTemplateList()
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

// 设为默认模板
const handleSetDefault = async (template) => {
  try {
    await setAsDefault(template.id, template.templateType)
    ElMessage.success('设置默认模板成功')
    fetchTemplateList()
  } catch (error) {
    ElMessage.error('设置失败')
  }
}

// 切换模板状态
const handleToggleTemplateStatus = async (template) => {
  try {
    const newStatus = template.status === 'active' ? 'inactive' : 'active'
    // 这里应该调用更新状态的API
    ElMessage.success(`${newStatus === 'active' ? '启用' : '禁用'}成功`)
    fetchTemplateList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除模板
const handleDeleteTemplate = async (template) => {
  try {
    await ElMessageBox.confirm('确定要删除这个模板吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteTemplate(template.id)
    ElMessage.success('删除成功')
    fetchTemplateList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 筛选模板
const filterTemplates = () => {
  if (!templateFilter.value) {
    filteredTemplateList.value = templateList.value
  } else {
    filteredTemplateList.value = templateList.value.filter(template =>
      template.templateType === templateFilter.value
    )
  }
}

// 工具函数
const getCertificateTypeTag = (type) => {
  const tagMap = {
    participation: 'primary',
    award: 'success',
    volunteer: 'warning',
    referee: 'info'
  }
  return tagMap[type] || 'info'
}

const getCertificateTypeText = (type) => {
  const textMap = {
    participation: '参赛证书',
    award: '获奖证书',
    volunteer: '志愿者证书',
    referee: '裁判证书'
  }
  return textMap[type] || '未知'
}

const getStatusTag = (status) => {
  const tagMap = {
    normal: 'success',
    revoked: 'danger',
    reissued: 'warning'
  }
  return tagMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    normal: '正常',
    revoked: '已撤销',
    reissued: '已重发'
  }
  return textMap[status] || '未知'
}

const getAwardLevelTag = (level) => {
  const tagMap = {
    '金牌': 'warning',
    '银牌': 'info',
    '铜牌': 'success',
    '参与奖': 'primary'
  }
  return tagMap[level] || 'info'
}

const getProjectName = (projectId) => {
  const project = projectOptions.value.find(p => p.value === projectId)
  return project ? project.label : '-'
}

const getTemplateName = (templateId) => {
  const template = templateList.value.find(t => t.id === templateId)
  return template ? template.templateName : '-'
}

const getUserName = (userId) => {
  const user = userOptions.value.find(u => u.value === userId)
  return user ? user.label : '-'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  return new Date(dateTime).toLocaleString()
}

// 其他事件处理
const handleSelectionChange = (selection) => {
  selectedCertificates.value = selection
}

const handleViewCertificateDetail = (certificate) => {
  currentCertificate.value = certificate
  showCertificateDetailDialog.value = true
}

const handlePreviewCertificate = (certificate) => {
  certificatePreviewUrl.value = `/api/certificates/${certificate.id}/preview`
  showCertificatePreviewDialog.value = true
}

const handleValidateCertificate = async () => {
  if (!validateForm.certificateNo) {
    ElMessage.warning('请输入证书编号')
    return
  }

  validating.value = true
  try {
    const response = await validateCertificate(validateForm.certificateNo)
    if (response.code === 200) {
      validateResult.value = response.data
    }
  } catch (error) {
    ElMessage.error('验证失败')
  } finally {
    validating.value = false
  }
}

const handlePreviewTemplate = () => {
  // 预览模板逻辑
  ElMessage.info('预览功能开发中')
}

const handlePreviewTemplateForm = () => {
  // 预览表单逻辑
  ElMessage.info('预览功能开发中')
}

const handleImportTemplate = () => {
  // 导入模板逻辑
  ElMessage.info('导入功能开发中')
}

const handleExportCertificates = () => {
  // 导出证书逻辑
  ElMessage.info('导出功能开发中')
}

const handleBatchDownload = async () => {
  // 批量下载逻辑
  ElMessage.info('批量下载功能开发中')
}

const handleBatchValidate = async () => {
  // 批量验证逻辑
  ElMessage.info('批量验证功能开发中')
}

const handleBatchRegenerate = async () => {
  // 批量重新生成逻辑
  ElMessage.info('批量重新生成功能开发中')
}

const handleBatchRevoke = async () => {
  // 批量撤销逻辑
  ElMessage.info('批量撤销功能开发中')
}

const handleCertificateTypeChange = () => {
  // 清空后续选择
  generateForm.userIds = []
  generateForm.projectId = null
  generateForm.awardId = null
  generateForm.awardLevel = ''
  generateForm.templateId = null
}

const nextGenerateStep = () => {
  if (generateStep.value < 2) {
    generateStep.value++
  }
}

const navigateTo = (path) => {
  router.push(path)
}

const handleLogout = () => {
  // 退出登录逻辑
  authStore.logout()
  router.push('/login')
}

// 监听标签页切换
watch(activeTab, (newTab) => {
  if (newTab === 'templates') {
    fetchTemplateList()
  }
})

// 初始化
onMounted(() => {
  fetchRecordList()
})
</script>

<style scoped>
/* 基础样式 */
* {
  font-family: 'PingFang SC', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  box-sizing: border-box;
}

/* 全局变量 */
:root {
  --primary-color: #2C5AA0;
  --primary-light: #E8EFF9;
  --primary-dark: #1E3D73;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --text-primary: #303133;
  --text-regular: #606266;
  --text-secondary: #909399;
  --text-placeholder: #C0C4CC;
  --border-light: #EBEEF5;
  --border-base: #DCDFE6;
  --border-lighter: #F2F6FC;
  --background-base: #F5F7FA;
  --background-light: #FAFAFA;
}

/* 容器布局 */
.app-container {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
  min-height: 100vh;
  background-color: var(--background-base);
}

/* 顶部导航栏 */
.header {
  grid-column: 1 / -1;
  background-color: var(--primary-color);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 100;
}

.logo {
  font-size: 20px;
  font-weight: 600;
  color: white;
  display: flex;
  align-items: center;
  gap: 12px;
  letter-spacing: 0.5px;
}

.flex-grow {
  flex-grow: 1;
}

/* 用户信息区域 */
.user-info {
  display: flex;
  align-items: center;
}

.user-avatar {
  display: flex;
  align-items: center;
  gap: 12px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 6px;
  transition: background-color 0.3s;
}

.user-avatar:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.username {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

/* 左侧导航栏 */
.sidebar {
  background-color: white;
  padding: 16px 0;
  border-right: 1px solid var(--border-light);
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
}

.menu-item {
  padding: 14px 24px;
  color: var(--text-regular);
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  font-weight: 500;
  position: relative;
}

.menu-item:hover {
  background-color: var(--primary-light);
  color: var(--primary-color);
}

.menu-item.active {
  background-color: var(--primary-light);
  color: var(--primary-color);
}

.menu-item.active::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background-color: var(--primary-color);
}

.menu-item span {
  font-size: 15px;
}

/* 主内容区 */
.content {
  padding: 24px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: 16px;
}

.page-title h1 {
  font-size: 28px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px 0;
}

.page-desc {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

/* 统计卡片区域 */
.statistics-row {
  margin-bottom: 0;
}

.stat-card {
  transition: all 0.3s ease;
  cursor: default;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 8px 0;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.success {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);
}

.stat-icon.warning {
  background: linear-gradient(135deg, #f2994a 0%, #f2c94c 100%);
}

.stat-icon.danger {
  background: linear-gradient(135deg, #eb3349 0%, #f45c43 100%);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  line-height: 1.2;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-top: 4px;
}

/* 标签页样式 */
:deep(.el-tabs--border-card) {
  border: 1px solid var(--border-base);
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-tab-pane) {
  padding: 20px;
}

/* 搜索容器 */
.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.advanced-search {
  margin-top: 20px;
}

/* 表格卡片 */
.table-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.el-card__body) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 表格工具栏 */
.table-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid var(--border-light);
}

.table-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.table-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 表格样式 */
:deep(.el-table) {
  flex: 1;
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: var(--background-light) !important;
  color: var(--text-primary);
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: var(--primary-light);
}

/* 表格操作按钮组 */
:deep(.el-button-group .el-button) {
  margin-left: 0;
}

:deep(.el-button-group .el-button + .el-button) {
  margin-left: 1px;
}

/* 分页容器 */
.pagination-container {
  padding: 16px 24px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid var(--border-light);
}

/* 批量操作栏 */
.batch-operations {
  padding: 16px 24px;
  background-color: var(--primary-light);
  border-top: 1px solid var(--border-light);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: var(--primary-color);
}

.batch-actions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

/* 模板头部 */
.template-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 5px;
}

.template-actions {
  display: flex;
  gap: 12px;
}

.template-filter {
  display: flex;
  align-items: center;
}

/* 模板网格 */
.template-grid {
  margin-bottom: 20px;
}

.template-card {
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
  overflow: hidden;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.template-card:hover .template-actions-overlay {
  opacity: 1;
}

.template-preview {
  position: relative;
}

.template-thumbnail {
  position: relative;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: var(--text-secondary);
}

.template-info {
  padding: 16px;
}

.template-name {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.template-meta {
  display: flex;
  gap: 8px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.template-description {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
}

.template-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: var(--text-placeholder);
}

.template-actions-overlay {
  position: absolute;
  top: 0;
  right: 0;
  padding: 8px;
  background: linear-gradient(to right, transparent, rgba(0, 0, 0, 0.7));
  opacity: 0;
  transition: opacity 0.3s ease;
  border-top-left-radius: 8px;
}

/* 生成步骤 */
.generate-steps {
  margin-bottom: 30px;
}

.step-content {
  padding: 20px 0;
}

.certificate-type-radio {
  display: block;
  width: 100%;
  margin-bottom: 16px;
  border: 1px solid var(--border-base);
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s ease;
}

.certificate-type-radio:hover {
  border-color: var(--primary-color);
  background-color: var(--primary-light);
}

.certificate-type-radio.is-checked {
  border-color: var(--primary-color);
  background-color: var(--primary-light);
}

.certificate-type-option {
  display: flex;
  align-items: center;
  gap: 16px;
}

.certificate-type-icon {
  font-size: 24px;
  color: var(--primary-color);
}

.certificate-type-text {
  flex: 1;
}

.certificate-type-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.certificate-type-desc {
  font-size: 14px;
  color: var(--text-secondary);
}

.user-option {
  display: flex;
  align-items: center;
}

.template-option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.form-tip {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  font-size: 14px;
  color: var(--text-secondary);
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background-color: var(--primary-color);
  color: white;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid var(--border-light);
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: var(--text-primary);
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input .el-input__inner) {
  border-radius: 4px;
}

/* 证书详情和预览 */
.certificate-detail {
  padding: 8px 0;
}

.certificate-preview {
  margin-top: 20px;
}

.certificate-preview-container {
  text-align: center;
}

.validate-form {
  padding: 20px 0;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
}

:deep(.el-descriptions__content) {
  color: var(--text-regular);
}

/* 对话框底部 */
.dialog-footer {
  text-align: right;
}

/* 按钮激活状态 */
:deep(.el-button.is-active) {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}

/* 消息提示样式 */
:deep(.el-message) {
  border-radius: 4px;
}

:deep(.el-message-box) {
  border-radius: 8px;
}

/* 桌面端样式优化 */
.app-container {
  grid-template-columns: 240px 1fr;
  grid-template-rows: 64px 1fr;
}

/* 动画效果 */
.el-fade-in-enter-active,
.el-fade-in-leave-active {
  transition: opacity 0.3s ease;
}

.el-fade-in-enter-from,
.el-fade-in-leave-to {
  opacity: 0;
}

.el-zoom-in-enter-active,
.el-zoom-in-leave-active {
  transition: all 0.3s ease;
}

.el-zoom-in-enter-from,
.el-zoom-in-leave-to {
  transform: scale(0.9);
  opacity: 0;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: var(--background-light);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: var(--border-base);
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: var(--text-placeholder);
}
</style>